//
//  HMComposePictureView.swift
//  Weibo24
//
//  Created by apple on 17/4/5.
//  Copyright © 2017年 itheima. All rights reserved.
//

import UIKit

//  自定义发微博的配图
class HMComposePictureView: UICollectionView {

    
    //  图片数据源
    lazy var images: [UIImage] = [UIImage]()
    //  点击加上完成闭包的回调
    var addPictureClosure: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //  每项的间距
        let itemMargin: CGFloat = 5
        //  每项的宽度和高度
        let itemWidth = (ScreenWidth - 2 * HomeCellMargin - 2 * itemMargin) / 3
        
        let flowLayout = UICollectionViewFlowLayout()
        //  设置每项的大小
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //  垂直间距
        flowLayout.minimumLineSpacing = itemMargin
        //  水平间距
        flowLayout.minimumInteritemSpacing = itemMargin
        
        
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        backgroundColor = UIColor.red
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        //  默认配图隐藏
        isHidden = true
        //  注册cell
        register(HMComposePictureViewCell.self, forCellWithReuseIdentifier: ComposePictureViewCellIdentifier)
        //  设置代理
        delegate = self
        //  设置数据源代理
        dataSource = self
    
    }
    
    //  添加图片
    func addImage(image: UIImage) {
        //  最多显示9张图片
        if images.count >= 9 {
            return
        }
        
        //  显示配图
        isHidden = false
        images.append(image)
        //  重新加载数据
        reloadData()
    }

}

//  MARK: ---  实现UICollectionViewDataSource
extension HMComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if images.count == 0 || images.count == 9 {
            return images.count
        }
        return images.count + 1
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ComposePictureViewCellIdentifier, for: indexPath) as! HMComposePictureViewCell
        
        if indexPath.item == images.count {
            //  最后一个图片
            cell.image = nil
        } else {
            //  获取对应的图片
            let image = images[indexPath.item]
            cell.image = image
            cell.indexPath = indexPath
            
            //  设置删除图片的闭包
            cell.deletePicClosure = {[weak self] (index: Int)->() in
                //  根据索引删除图片
                self?.images.remove(at: index)
                //  数组没有图片
                if self?.images.count == 0 {
                    //  隐藏当前配图
                    self?.isHidden = true
                }
                
                self?.reloadData()
            }
            
        }
        
       
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //  判断你点击是否是最后一cell
        if indexPath.item == images.count {
            //  最后一个图片
            addPictureClosure?()
        }
    }
    
}

//  自定义配图cell
class HMComposePictureViewCell: UICollectionViewCell {
    //  MARK: ---   懒加载控件
    //  图片
    fileprivate lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //  删除图片按钮
    fileprivate lazy var deleteButton: UIButton = {
        let button = UIButton()
        //  添加点击事件
        button.addTarget(self, action: #selector(deletePicAction), for: .touchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return button
    }()
    //  记录当前的indexPath
    var indexPath: IndexPath?
    
    //  删除图片的闭包
    var deletePicClosure: ((Int)->())?
    
    var image: UIImage? {
        didSet {
            if image == nil {
                //  需要设置加号图片
                imageView.image = UIImage(named: "compose_pic_add")
                //  隐藏删除按钮
                deleteButton.isHidden = true
            } else {
                imageView.image = image
                //  其他图片显示删除按钮
                deleteButton.isHidden = false
            }
            
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        deleteButton.snp.makeConstraints { (make) in
            make.top.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
    //  MARK: ---删除图片
    @objc private func deletePicAction() {
        //  删除对应的图片
        if let currentIndexPath = indexPath {
            //  回调删除图片索引
            deletePicClosure?(currentIndexPath.item)
        }
        
    }
}



